from __future__ import annotations

import os
from io import FileIO
from pathlib import Path
from typing import AnyStr, Union

'''
Lark Grammar
'''


class Grammar:

    DEFAULT_GRAMMAR = os.path.join(
        os.path.dirname(os.path.abspath(__file__)),
        'grammar.lark'
    )

    def __init__(self, grammar: AnyStr = ""):
        self.grammar = Grammar._load_grammar(grammar)

    @staticmethod
    def _load_grammar(grammar: Union[Path, AnyStr] = ""):
        grammar_path = grammar if isinstance(grammar, Path) else Path(grammar)
        if grammar_path.exists() and grammar_path.is_file():
            return open(grammar_path, mode='r', encoding='utf8').read()
        elif grammar:
            return grammar
        return open(Grammar.DEFAULT_GRAMMAR, mode='r', encoding='utf8').read()

    def update(self, other: Grammar):
        self.grammar += other.grammar
        unique_lines = set(self.grammar.splitlines())
        self.grammar = "\n".join(unique_lines)
